package ink.lovejinhu.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jinhu
 * created 2021-07-20 17:21
 */
public class SaleTicketUseLock {
    /**
     * 多线程卖票
     *
     * @param args
     */
    public static void main(String[] args) {
        Ticket01 ticket01 = new Ticket01(40);
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket01.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller01").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket01.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller02").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket01.sale();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "saller03").start();
    }

}

class Ticket01 {
    public int count;

    public Ticket01(int count) {
        this.count = count;
    }

    public ReentrantLock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        if (count > 0) {
            System.out.println(Thread.currentThread().getName() + "：售卖第" + count + "张票");
            count--;
        }
        lock.unlock();
    }
}
